<?php

namespace IDock\Insurance\DAJIA\Request;

use IDock\Http\Request;
use IDock\Http\RequestFormat;
use IDock\Http\RequestMethod;
use IDock\Http\Response;

/**
 * 大家请求总类
 */
class AllDAJIARequest extends Request {

    protected $code;

    protected $method = RequestMethod::POST;

    protected $format = RequestFormat::FORM;

    public function loadConfig(array $config): Request
    {
        $this->gateway = $config['gateway'] ?? '';

        $this->logsDir = $config['logsDir'] ?? '';

        $this->timeout = $config['timeout'] ?? '';

        $this->proxy = $config['proxy'];

        $this->proxyPW = $config['proxyPW'] ?? '';

        $this->proxyAccount = $config['proxyAccount'] ?? '';

        $this->format = RequestFormat::JSON;

        return  $this;
    }

    /**
     * @return mixed
     */
    public function getCode()
    {
        return $this->code;
    }

    public function requestLogs($uuid,$inLog = true)
    {
        if (!$this->logsFile) {
            return;
        }

        if ($this->urlTip) {
            $url = $this->gateway;
            $urlLogs = date('Y-m-d H:i:s') . " FUN_TIPS " . $uuid . " " . $this->urlTip . ' ' . $url;
        } else {
            $urlLogs = date('Y-m-d H:i:s') . " URL      " . $uuid . " " . $this->gateway;
        }
        file_put_contents($this->logsFile, "\r\n", FILE_APPEND);


        file_put_contents($this->logsFile, $urlLogs . "\r\n", FILE_APPEND);

        //header 日记
        if ($this->headers) {
            $encLogs = date('Y-m-d H:i:s') . " HEADER   " . $uuid . " " . json_encode($this->getHeaders(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            file_put_contents($this->logsFile, $encLogs . "\r\n", FILE_APPEND);
        }

        if (!$inLog) {
            return;
        }

        if (!$this->inLog) {
            return;
        }


        if ($this->preParameter != $this->bizParam) {
            $encLogs = date('Y-m-d H:i:s') . " ENCRYPT  " . $uuid . " " . json_encode($this->preParameter, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            file_put_contents($this->logsFile, $encLogs . "\r\n", FILE_APPEND);
        }
        //过滤加密请求
        //if ($this->bizParam ?? '') {
        //    $biz = $this->bizParam;
        //
        //    if (is_array($biz)) {
        //        $biz = json_encode($biz, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        //    }
        //
        //    $reqLogs = date('Y-m-d H:i:s') . " REQUEST  " . $uuid . " " . $biz;
        //    file_put_contents($this->logsFile, $reqLogs . "\r\n", FILE_APPEND);
        //}
    }

    public function responseLogs($uuid, $data)
    {
        if (!$this->logsFile) {
            return;
        }
        $data = str_replace(["\r\n"],[''],$data);
        $repLogs = date('Y-m-d H:i:s') . " RESPONSE " . $uuid . " " . $data;

        file_put_contents($this->logsFile, $repLogs . "\r\n", FILE_APPEND);
    }
}
